package day1.HomeWork;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * ClassName：Test4chat
 *
 * @Author：小鱼
 * @Create：2025-08-25 17:01
 */
public class Test4chat implements Runnable{
    private Socket clientSocket;
    private BufferedReader in;
    private PrintWriter out;

    public Test4chat(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try {
            // 获取输入输出流
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(clientSocket.getOutputStream(), true);

            String inputLine;
            // 读取客户端发送的信息
            while ((inputLine = in.readLine()) != null) {
                // 显示收到的信息
                System.out.println("收到客户端" + clientSocket.getInetAddress().getHostAddress() + "的信息：" + inputLine);

                // 如果收到quit，则断开当前客户端连接
                if ("quit".equalsIgnoreCase(inputLine)) {
                    System.out.println("客户端" + clientSocket.getInetAddress().getHostAddress() + "已断开连接");
                    out.println("服务器已收到断开请求，连接将关闭");
                    break;
                }

                // 字符串反转
                String reversed = new StringBuilder(inputLine).reverse().toString();

                // 将反转后的字符串返回给客户端
                out.println("服务器已将字符串反转为：" + reversed);
            }

            // 关闭资源
            in.close();
            out.close();
            clientSocket.close();
            System.out.println("客户端" + clientSocket.getInetAddress().getHostAddress() + "连接已关闭");

        } catch (IOException e) {
            System.out.println("与客户端" + clientSocket.getInetAddress().getHostAddress() + "连接发生异常：" + e.getMessage());
        }
    }
}